package com.saifan.wyy_ov.ui.communitylife;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.http.RequestParams;
import com.saifan.wyy_ov.R;
import com.saifan.wyy_ov.data.bean.BBSPublishBean;
import com.saifan.wyy_ov.data.bean.BBSThemesBean;
import com.saifan.wyy_ov.config.Api;
import com.saifan.wyy_ov.model.impl.GetData;
import com.saifan.wyy_ov.model.interfaces.IGetData;
import com.saifan.wyy_ov.model.interfaces.ResponseData;
import com.saifan.wyy_ov.ui.album.ui.PhotoAlbumActivity;
import com.saifan.wyy_ov.ui.view.BaseActivity;
import com.saifan.wyy_ov.ui.view.BootstrapButton;
import com.saifan.wyy_ov.utils.CameraUtil;
import com.saifan.wyy_ov.utils.FileUtils;
import com.saifan.wyy_ov.utils.GsonUtils;
import com.saifan.wyy_ov.utils.PictureUtil;
import com.saifan.wyy_ov.utils.StringUtil;
import com.saifan.wyy_ov.utils.ToastUtil;

import java.io.File;
import java.util.ArrayList;

/**
 * @version V1.0.0
 * @author: Wangli
 * @date: 2015-6-9 21:32:21
 * @descrption
 */

public class BBSPublishActivity extends BaseActivity {
    private android.support.v7.widget.Toolbar toolbar;
    private BBSPublisAdapter adapter;
    private android.widget.EditText content;
    private android.widget.GridView imagegrid;
    private com.saifan.wyy_ov.ui.view.BootstrapButton publish;
    private ArrayList<String> selectList;
    private final int SELECT_IMG = 1;
    private final int SELECT_PHOTO_TAKEPHOTO = 2;
    private String picName = "";//图片路径
    private int selectPostion = -1;
    private android.widget.TextView tip;
    private IGetData getData;
    private BBSPublishBean bean;
    private BBSThemesBean bbsThemesBean;
    private EditText title;
    private TextView titletip;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bbsThemesBean = (BBSThemesBean) getIntent().getExtras().getSerializable("data");
        setupViews();
    }

    private void setupViews() {
        setContentView(R.layout.activity_bbspublish);
        this.titletip = (TextView) findViewById(R.id.title_tip);
        this.title = (EditText) findViewById(R.id.title);
        this.tip = (TextView) findViewById(R.id.tip);
        this.publish = (BootstrapButton) findViewById(R.id.publish);
        this.imagegrid = (GridView) findViewById(R.id.image_grid);
        this.content = (EditText) findViewById(R.id.content);
        this.toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        selectList = new ArrayList<String>();
        adapter = new BBSPublisAdapter(selectList, BBSPublishActivity.this);
        imagegrid.setAdapter(adapter);
        imagegrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (selectList.size() < 4) {
                    selectPostion = position - 1;
                    if (position == 0) {
                        showSelectImgDialog(false);
                    } else {
                        showSelectImgDialog(true);
                    }
                } else {
                    selectPostion = position;
                    showSelectImgDialog(true);
                }

            }
        });
        title.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                titletip.setText(String.format(getResources().getString(R.string.publish_content_length), s.length(), 20));
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        content.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                tip.setText(String.format(getResources().getString(R.string.publish_content_length), s.length(), 180));
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        publish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submitData();
            }
        });
    }


    //显示选择图片的对话框
    private void showSelectImgDialog(boolean hasDelete) {
        String[] items;
        if (hasDelete)
            items = new String[]{"从相册中选择", "拍照", "删除"};
        else
            items = new String[]{"从相册中选择", "拍照"};
        AlertDialog dialog = new AlertDialog.Builder(BBSPublishActivity.this)
                .setTitle("选择图片")
                .setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {
                            selectImg();
                        } else if (which == 2) {
                            selectList.remove(selectPostion);
                            adapter.list = selectList;
                            adapter.notifyDataSetChanged();
                        } else {
                            cammerPermission(SELECT_PHOTO_TAKEPHOTO);
                        }
                        dialog.dismiss();
                    }
                })
                .show();
    }

    //从相册中选择图片
    private void selectImg() {

        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, SELECT_IMG);
                return;
            } else {
                Intent intent = new Intent(BBSPublishActivity.this, PhotoAlbumActivity.class);
                intent.putStringArrayListExtra("data", selectList);
                intent.putExtra("count", 4);
                startActivityForResult(intent, SELECT_IMG);
            }
        } else {
            Intent intent = new Intent(BBSPublishActivity.this, PhotoAlbumActivity.class);
            intent.putStringArrayListExtra("data", selectList);
            intent.putExtra("count", 4);
            startActivityForResult(intent, SELECT_IMG);
        }


    }

    public void cammerPermission(int position) {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, position);
                return;
            } else {



                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, SELECT_PHOTO_TAKEPHOTO);


            }
        } else {

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent, SELECT_PHOTO_TAKEPHOTO);


        }

    }

    public void storePermission(int position) {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, position);
                return;
            } else {
                Intent intent = new Intent(this, PhotoAlbumActivity.class);
                intent.putStringArrayListExtra("data", selectList);
                startActivityForResult(intent, SELECT_IMG);
            }
        } else {
            Intent intent = new Intent(this, PhotoAlbumActivity.class);
            intent.putStringArrayListExtra("data", selectList);
            startActivityForResult(intent, SELECT_IMG);
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == SELECT_PHOTO_TAKEPHOTO) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, SELECT_PHOTO_TAKEPHOTO);


            } else {
                // Permission Denied
                Toast.makeText(this, "您禁用摄像头", Toast.LENGTH_SHORT)
                        .show();

            }
        } else {

            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
                Intent intent = new Intent(BBSPublishActivity.this, PhotoAlbumActivity.class);
                intent.putStringArrayListExtra("data", selectList);
                intent.putExtra("count", 4);
                startActivityForResult(intent, SELECT_IMG);


            } else {
                // Permission Denied
                Toast.makeText(this, "您禁用本地存储读写", Toast.LENGTH_SHORT)
                        .show();

            }
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == SELECT_IMG) {
                this.selectList = data.getStringArrayListExtra("data");
                adapter.list = selectList;
                adapter.notifyDataSetChanged();
            } else if (requestCode == SELECT_PHOTO_TAKEPHOTO) {
                Bitmap bitmap = data.getParcelableExtra("data") ;
                File file = FileUtils. bitmapToFile(bitmap);
                FileUtils.toAlbum(this,file);
                picName=file.getAbsolutePath();
                if (selectPostion == -1) {
                    this.selectList.add(picName);
                } else {
                    this.selectList.set(selectPostion, picName);
                }
                adapter.list = selectList;
                adapter.notifyDataSetChanged();
            }
        }
    }

    public void submitData() {
        if (StringUtil.isNullOrEmpty(title.getText().toString().trim())){
            ToastUtil.showToast(BBSPublishActivity.this, "请输入帖子标题");
            return;
        }
        if (StringUtil.isNullOrEmpty(content.getText().toString().trim())) {
            ToastUtil.showToast(BBSPublishActivity.this, "请输入帖子内容");
            return;
        }
        if (getData == null)
            getData = new GetData();
        if (bean == null) {
            bean = new BBSPublishBean();
            bean.setFTB_LTBKWJ(bbsThemesBean.getLTBK_ZJ());
            bean.setFTB_KHWJ(getRoomInfoBean().getWYKHDA_ZJ());
            bean.setXMBS(getRoomInfoBean().getXMBS());
        }
        bean.setFTB_BT(title.getText().toString().trim());
        bean.setFTB_LR(content.getText().toString().trim());
        RequestParams params = new RequestParams();
        params.addBodyParameter("Posts", GsonUtils.toJson(bean));
        for (int i = 0; i < selectList.size(); i++) {
            File file = new File(PictureUtil.getCompressBitmap(selectList.get(i)));
            if (file.exists()) {
                params.addBodyParameter(file.getName(), file);
            }
        }
        getData.getDataJson(BBSPublishActivity.this, Api.BBS.POSTSSUBMIT, params, "正在请求...", new ResponseData() {
            @Override
            public void onSuccess(String json) {
                ToastUtil.showToast(BBSPublishActivity.this, "发布成功");
                BBSPublishActivity.this.finish();
            }

            @Override
            public void onFailed(String str) {

            }
        });
    }
}
